<template>
    <div class="cache-management">

        <div class="management-content">
            <!-- 示例数据提示 -->
            <div v-if="isUsingSampleData" class="sample-data-notice">
                <el-alert
                    title="示例数据模式"
                    description="当前使用示例数据，因为后端服务暂时不可用。您可以正常浏览和测试页面功能。"
                    type="info"
                    :closable="false"
                    show-icon>
                </el-alert>
            </div>

            <!-- 加载状态 -->
            <div v-if="isLoading" class="loading-state">
                <el-icon class="loading-icon">
                    <Loading />
                </el-icon>
                <p>正在加载缓存数据...</p>
            </div>

            <!-- 缓存监控组件 -->
            <div class="cache-monitor">
                <div class="monitor-header">
                    <h3>缓存监控</h3>
                    <el-button size="small" @click="refreshStats">刷新</el-button>
                </div>

                <div class="monitor-content">
                    <!-- Service Worker状态 -->
                    <div class="status-section">
                        <h4>Service Worker状态</h4>
                        <div class="status-grid">
                            <div class="status-item">
                                <span class="label">支持状态:</span>
                                <span class="value"
                                    :class="{ success: swStatus.isSupported, error: !swStatus.isSupported }">
                                    {{ swStatus.isSupported ? '支持' : '不支持' }}
                                </span>
                            </div>
                            <div class="status-item">
                                <span class="label">注册状态:</span>
                                <span class="value"
                                    :class="{ success: swStatus.isRegistered, error: !swStatus.isRegistered }">
                                    {{ swStatus.isRegistered ? '已注册' : '未注册' }}
                                </span>
                            </div>
                            <div class="status-item">
                                <span class="label">网络状态:</span>
                                <span class="value" :class="{ success: swStatus.isOnline, error: !swStatus.isOnline }">
                                    {{ swStatus.isOnline ? '在线' : '离线' }}
                                </span>
                            </div>
                            <div class="status-item">
                                <span class="label">通知权限:</span>
                                <span class="value" :class="getPermissionClass(swStatus.permission)">
                                    {{ getPermissionText(swStatus.permission) }}
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- HTTP缓存统计 -->
                    <div class="status-section">
                        <h4>HTTP缓存统计</h4>
                        <div class="cache-stats">
                            <div class="stat-item">
                                <span class="label">缓存项数:</span>
                                <span class="value">{{ httpCacheStats.size }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="label">缓存键:</span>
                                <span class="value">{{ httpCacheStats.keys.length }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- 缓存操作 -->
                    <div class="actions-section">
                        <h4>缓存操作</h4>
                        <div class="action-buttons">
                            <el-button size="small" @click="clearHttpCache">清除HTTP缓存</el-button>
                            <el-button size="small" @click="clearAllCaches">清除所有缓存</el-button>
                            <el-button size="small" @click="requestNotificationPermission">请求通知权限</el-button>
                            <el-button size="small" @click="updateServiceWorker">更新Service Worker</el-button>
                        </div>
                    </div>

                    <!-- 缓存详情 -->
                    <div class="details-section" v-if="showDetails">
                        <h4>缓存详情</h4>
                        <div class="cache-details">
                            <div v-for="key in httpCacheStats.keys" :key="key" class="cache-item">
                                <span class="cache-key">{{ key }}</span>
                                <el-button size="mini" @click="deleteCache(key)">删除</el-button>
                            </div>
                        </div>
                    </div>

                    <!-- 显示详情按钮 -->
                    <div class="toggle-details">
                        <el-button size="small" @click="showDetails = !showDetails">
                            {{ showDetails ? '隐藏详情' : '显示详情' }}
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- 缓存统计图表 -->
            <div class="cache-stats">
                <div class="stats-grid">
                    <div class="stat-card">
                        <h3>缓存命中率</h3>
                        <div class="stat-value">{{ cacheHitRate }}%</div>
                        <div class="stat-desc">缓存命中率越高，性能越好</div>
                    </div>
                    <div class="stat-card">
                        <h3>缓存大小</h3>
                        <div class="stat-value">{{ cacheSize }}MB</div>
                        <div class="stat-desc">当前缓存占用的存储空间</div>
                    </div>
                    <div class="stat-card">
                        <h3>离线支持</h3>
                        <div class="stat-value">{{ offlineSupport ? '支持' : '不支持' }}</div>
                        <div class="stat-desc">是否支持离线访问</div>
                    </div>
                    <div class="stat-card">
                        <h3>更新频率</h3>
                        <div class="stat-value">{{ updateFrequency }}</div>
                        <div class="stat-desc">缓存自动更新频率</div>
                    </div>
                </div>
            </div>

            <!-- 缓存配置 -->
            <div class="cache-config">
                <h2>缓存配置</h2>
                <el-form :model="cacheConfig" label-width="120px">
                    <el-form-item label="静态资源缓存">
                        <el-select v-model="cacheConfig.staticCache" placeholder="选择缓存策略">
                            <el-option label="永久缓存" value="permanent" />
                            <el-option label="1小时" value="1h" />
                            <el-option label="1天" value="1d" />
                            <el-option label="1周" value="1w" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="API缓存时间">
                        <el-input-number v-model="cacheConfig.apiCacheTime" :min="1" :max="60" label="分钟" />
                        <span class="unit">分钟</span>
                    </el-form-item>

                    <el-form-item label="动态内容缓存">
                        <el-select v-model="cacheConfig.dynamicCache" placeholder="选择缓存策略">
                            <el-option label="5分钟" value="5m" />
                            <el-option label="10分钟" value="10m" />
                            <el-option label="30分钟" value="30m" />
                            <el-option label="1小时" value="1h" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="自动清理">
                        <el-switch v-model="cacheConfig.autoCleanup" />
                        <span class="desc">自动清理过期缓存</span>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="saveConfig">保存配置</el-button>
                        <el-button @click="resetConfig">重置配置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 缓存日志 -->
            <div class="cache-logs">
                <h2>缓存日志</h2>
                <div class="logs-container">
                    <div v-for="log in cacheLogs" :key="log.id" class="log-item" :class="log.type">
                        <div class="log-time">{{ formatTime(log.timestamp) }}</div>
                        <div class="log-message">{{ log.message }}</div>
                        <div class="log-type">{{ log.type }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { get, post, API_PATHS } from '@/utils/api'

// 缓存配置
const cacheConfig = ref({
    staticCache: 'permanent',
    apiCacheTime: 10,
    dynamicCache: '5m',
    autoCleanup: true
})

// 缓存统计
const cacheHitRate = ref(85)
const cacheSize = ref(12.5)
const offlineSupport = ref(true)
const updateFrequency = ref('5分钟')

// 类型定义
interface CacheStats {
  hitRate: number
  size: number
  offlineSupport: boolean
  updateFrequency: string
  totalRequests: number
  cachedRequests: number
}

interface CacheConfig {
  staticCache: string
  apiCacheTime: number
  dynamicCache: string
  autoCleanup: boolean
}

interface CacheLog {
  id: number
  timestamp: number
  message: string
  type: 'info' | 'success' | 'warning' | 'error'
}

// 示例数据
const sampleCacheStats: CacheStats = {
  hitRate: 85,
  size: 12.5,
  offlineSupport: true,
  updateFrequency: '5分钟',
  totalRequests: 1250,
  cachedRequests: 1062
}

const sampleCacheConfig: CacheConfig = {
  staticCache: 'permanent',
  apiCacheTime: 10,
  dynamicCache: '5m',
  autoCleanup: true
}

const sampleCacheLogs: CacheLog[] = [
  {
    id: 1,
    timestamp: Date.now() - 1000 * 60 * 5,
    message: 'Service Worker 已注册并开始缓存静态资源',
    type: 'info'
  },
  {
    id: 2,
    timestamp: Date.now() - 1000 * 60 * 3,
    message: 'API缓存命中率提升至85%',
    type: 'success'
  },
  {
    id: 3,
    timestamp: Date.now() - 1000 * 60 * 1,
    message: '清理过期缓存，释放2.3MB空间',
    type: 'warning'
  },
  {
    id: 4,
    timestamp: Date.now() - 1000 * 30,
    message: '缓存配置已更新',
    type: 'success'
  }
]

// 缓存日志
const cacheLogs = ref<CacheLog[]>([])

// 缓存监控状态
const swStatus = ref({
    isSupported: false,
    isRegistered: false,
    isOnline: false,
    permission: 'default' as NotificationPermission
})

// HTTP缓存统计
const httpCacheStats = ref({
    size: 0,
    keys: [] as string[]
})

// 显示详情
const showDetails = ref(false)
// 是否正在使用示例数据
const isUsingSampleData = ref(false)
// 加载状态
const isLoading = ref(false)

/**
 * 使用示例数据
 * @description 当API请求失败时使用示例数据
 */
const useSampleData = () => {
  isUsingSampleData.value = true
  ElMessage.warning('后端服务暂时不可用，使用示例数据')
}

/**
 * 获取缓存统计
 * @description 从后端API获取缓存统计数据
 */
const fetchCacheStats = async () => {
  try {
    isLoading.value = true
    const response = await get<CacheStats>(API_PATHS.CACHE.STATS, {
      timeout: 8000,
      retry: 2
    })

    if (response.success && response.data) {
      cacheHitRate.value = response.data.hitRate
      cacheSize.value = response.data.size
      offlineSupport.value = response.data.offlineSupport
      updateFrequency.value = response.data.updateFrequency
      console.log('获取缓存统计成功:', response.data)
    } else {
      console.error('获取缓存统计失败:', response.error)
      useSampleData()
      // 使用示例数据
      cacheHitRate.value = sampleCacheStats.hitRate
      cacheSize.value = sampleCacheStats.size
      offlineSupport.value = sampleCacheStats.offlineSupport
      updateFrequency.value = sampleCacheStats.updateFrequency
    }
  } catch (error) {
    console.error('获取缓存统计异常:', error)
    useSampleData()
    // 使用示例数据
    cacheHitRate.value = sampleCacheStats.hitRate
    cacheSize.value = sampleCacheStats.size
    offlineSupport.value = sampleCacheStats.offlineSupport
    updateFrequency.value = sampleCacheStats.updateFrequency
  } finally {
    isLoading.value = false
  }
}

/**
 * 获取缓存配置
 * @description 从后端API获取缓存配置
 */
const fetchCacheConfig = async () => {
  try {
    const response = await get<CacheConfig>(API_PATHS.CACHE.CONFIG, {
      timeout: 8000,
      retry: 2
    })

    if (response.success && response.data) {
      cacheConfig.value = response.data
      console.log('获取缓存配置成功:', response.data)
    } else {
      console.error('获取缓存配置失败:', response.error)
      useSampleData()
      // 使用示例数据
      cacheConfig.value = { ...sampleCacheConfig }
    }
  } catch (error) {
    console.error('获取缓存配置异常:', error)
    useSampleData()
    // 使用示例数据
    cacheConfig.value = { ...sampleCacheConfig }
  }
}

/**
 * 获取缓存日志
 * @description 从后端API获取缓存日志
 */
const fetchCacheLogs = async () => {
  try {
    const response = await get<CacheLog[]>(API_PATHS.CACHE.LOGS, {
      timeout: 8000,
      retry: 2
    })

    if (response.success && response.data) {
      cacheLogs.value = response.data
      console.log('获取缓存日志成功:', response.data)
    } else {
      console.error('获取缓存日志失败:', response.error)
      useSampleData()
      // 使用示例数据
      cacheLogs.value = [...sampleCacheLogs]
    }
  } catch (error) {
    console.error('获取缓存日志异常:', error)
    useSampleData()
    // 使用示例数据
    cacheLogs.value = [...sampleCacheLogs]
  }
}

// 保存配置
const saveConfig = async () => {
    try {
        isLoading.value = true
        const response = await post<{ message: string }>(API_PATHS.CACHE.SAVE_CONFIG, cacheConfig.value, {
            timeout: 8000,
            retry: 2
        })

        if (response.success) {
            ElMessage.success(response.data?.message || '缓存配置已保存')
            console.log('保存缓存配置成功:', cacheConfig.value)
            
            // 重新获取配置以确保同步
            await fetchCacheConfig()
        } else {
            ElMessage.error(response.error || '保存配置失败')
            console.error('保存缓存配置失败:', response.error)
        }
    } catch (error) {
        ElMessage.error('网络请求失败，请稍后重试')
        console.error('保存缓存配置异常:', error)
        
        // 开发环境下输出详细错误信息
        if (import.meta.env.DEV) {
            console.error('详细错误信息:', error)
        }
    } finally {
        isLoading.value = false
    }
}

// 重置配置
const resetConfig = () => {
    cacheConfig.value = {
        staticCache: 'permanent',
        apiCacheTime: 10,
        dynamicCache: '5m',
        autoCleanup: true
    }
    ElMessage.success('配置已重置')
}

// 刷新缓存统计
const refreshStats = async () => {
    try {
        isLoading.value = true
        ElMessage.info('刷新缓存统计...')
        
        const response = await post<{ message: string }>(API_PATHS.CACHE.REFRESH, {}, {
            timeout: 8000,
            retry: 2
        })

        if (response.success) {
            ElMessage.success(response.data?.message || '缓存统计刷新成功')
            console.log('刷新缓存统计成功')
            
            // 重新获取统计数据
            await fetchCacheStats()
        } else {
            ElMessage.error(response.error || '刷新缓存统计失败')
            console.error('刷新缓存统计失败:', response.error)
        }
    } catch (error) {
        ElMessage.error('网络请求失败，请稍后重试')
        console.error('刷新缓存统计异常:', error)
        
        // 开发环境下输出详细错误信息
        if (import.meta.env.DEV) {
            console.error('详细错误信息:', error)
        }
    } finally {
        isLoading.value = false
    }
}

// 清除HTTP缓存
const clearHttpCache = async () => {
    try {
        isLoading.value = true
        const response = await post<{ message: string }>(API_PATHS.CACHE.CLEAR_HTTP, {}, {
            timeout: 8000,
            retry: 2
        })

        if (response.success) {
            ElMessage.success(response.data?.message || 'HTTP缓存已清除')
            console.log('清除HTTP缓存成功')
            
            // 更新本地缓存统计
            httpCacheStats.value = { size: 0, keys: [] }
            
            // 重新获取统计数据
            await fetchCacheStats()
        } else {
            ElMessage.error(response.error || '清除HTTP缓存失败')
            console.error('清除HTTP缓存失败:', response.error)
        }
    } catch (error) {
        ElMessage.error('网络请求失败，请稍后重试')
        console.error('清除HTTP缓存异常:', error)
        
        // 开发环境下输出详细错误信息
        if (import.meta.env.DEV) {
            console.error('详细错误信息:', error)
        }
    } finally {
        isLoading.value = false
    }
}

// 清除所有缓存
const clearAllCaches = async () => {
    try {
        isLoading.value = true
        const response = await post<{ message: string }>(API_PATHS.CACHE.CLEAR_ALL, {}, {
            timeout: 8000,
            retry: 2
        })

        if (response.success) {
            ElMessage.success(response.data?.message || '所有缓存已清除')
            console.log('清除所有缓存成功')
            
            // 更新本地缓存统计
            httpCacheStats.value = { size: 0, keys: [] }
            
            // 重新获取统计数据
            await fetchCacheStats()
        } else {
            ElMessage.error(response.error || '清除所有缓存失败')
            console.error('清除所有缓存失败:', response.error)
        }
    } catch (error) {
        ElMessage.error('网络请求失败，请稍后重试')
        console.error('清除所有缓存异常:', error)
        
        // 开发环境下输出详细错误信息
        if (import.meta.env.DEV) {
            console.error('详细错误信息:', error)
        }
    } finally {
        isLoading.value = false
    }
}

// 请求通知权限
const requestNotificationPermission = () => {
    Notification.requestPermission().then(permission => {
        swStatus.value.permission = permission
        ElMessage.success('通知权限已请求')
    }).catch(err => {
        ElMessage.error('请求通知权限失败: ' + err)
    })
}

// 更新Service Worker
const updateServiceWorker = () => {
    ElMessage.info('尝试更新Service Worker...')
    // 模拟更新逻辑
    setTimeout(() => {
        ElMessage.success('Service Worker 已更新')
    }, 1000)
}

// 删除单个缓存
const deleteCache = async (key: string) => {
    try {
        isLoading.value = true
        ElMessage.info(`尝试删除缓存: ${key}`)
        
        const response = await post<{ message: string }>(API_PATHS.CACHE.DELETE(key), {}, {
            timeout: 8000,
            retry: 2
        })

        if (response.success) {
            ElMessage.success(response.data?.message || `缓存 ${key} 已删除`)
            console.log('删除缓存成功:', key)
            
            // 从本地缓存统计中移除
            httpCacheStats.value.keys = httpCacheStats.value.keys.filter(k => k !== key)
            httpCacheStats.value.size = Math.max(0, httpCacheStats.value.size - 1)
            
            // 重新获取统计数据
            await fetchCacheStats()
        } else {
            ElMessage.error(response.error || `删除缓存 ${key} 失败`)
            console.error('删除缓存失败:', response.error)
        }
    } catch (error) {
        ElMessage.error('网络请求失败，请稍后重试')
        console.error('删除缓存异常:', error)
        
        // 开发环境下输出详细错误信息
        if (import.meta.env.DEV) {
            console.error('详细错误信息:', error)
        }
    } finally {
        isLoading.value = false
    }
}

// 格式化时间
const formatTime = (timestamp: number): string => {
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN')
}

// 获取权限类
const getPermissionClass = (permission: NotificationPermission) => {
    if (permission === 'granted') {
        return 'success'
    } else if (permission === 'denied') {
        return 'error'
    } else {
        return 'default'
    }
}

// 获取权限文本
const getPermissionText = (permission: NotificationPermission) => {
    if (permission === 'granted') {
        return '已授权'
    } else if (permission === 'denied') {
        return '已拒绝'
    } else {
        return '未授权'
    }
}

// 初始化
onMounted(async () => {
    console.log('缓存管理页面已加载')

    // 检查 Service Worker 状态
    swStatus.value.isSupported = 'serviceWorker' in navigator
    swStatus.value.isOnline = navigator.onLine
    swStatus.value.permission = Notification.permission

    // 检查 Service Worker 注册状态
    if (swStatus.value.isSupported) {
        try {
            const registration = await navigator.serviceWorker.getRegistration()
            swStatus.value.isRegistered = !!registration
        } catch (error) {
            console.error('检查Service Worker注册状态失败:', error)
            swStatus.value.isRegistered = false
        }
    }

    // 获取缓存数据
    await Promise.all([
        fetchCacheStats(),
        fetchCacheConfig(),
        fetchCacheLogs()
    ])

    // 初始化 HTTP 缓存统计（如果API失败，使用示例数据）
    if (httpCacheStats.value.size === 0 && !isUsingSampleData.value) {
        httpCacheStats.value = {
            size: 100,
            keys: ['/api/data', '/static/image.jpg', '/index.html']
        }
    }
})
</script>

<style scoped lang="scss">
// 导入缓存管理页面样式
@use '../../assets/styles/admin/_cache-management';
</style>